<?php

namespace App\Http\Controllers\School;

use App\Http\Requests\School\EditFoodType;
use App\Http\Requests\School\StoreFoodType;
use App\Http\Resources\School\FoodTypeResource;
use App\Models\FoodType;
use App\Models\SchoolAdminLog;
use Illuminate\Http\Request;

/**
 * Class FoodTypeController
 * @package App\Http\Controllers\School
 * 学校后台菜品种类管理
 */
class FoodTypeController extends BaseController
{
    /**
     * @param Request $request
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     * 菜品种类列表
     */
    public function index(Request $request)
    {
        $foodTypes = FoodType::orderBy('sort', 'asc')
            ->where('school_id', \Auth::user()->school_id)
            ->with('school')
            ->nameLike($request->name)
            ->paginate($request->size);
        return FoodTypeResource::collection($foodTypes);
    }

    /**
     * @param StoreFoodType $request
     * @return FoodTypeResource
     * 新增菜品种类
     */
    public function store(StoreFoodType $request)
    {
        $foodType = FoodType::create(array_merge($request->all(), [
            'school_id' => \Auth::user()->school_id
        ]));
        SchoolAdminLog::Log('新增菜品种类: ' . $foodType->name . ', id为: ' . $foodType->id);
        return new FoodTypeResource($foodType);
    }

    /**
     * @param EditFoodType $request
     * @param FoodType $foodType
     * @return FoodTypeResource
     * 编辑菜品种类
     */
    public function update(EditFoodType $request, FoodType $foodType)
    {
        $foodType->fill($request->all());
        $foodType->save();
        SchoolAdminLog::Log('编辑菜品种类: ' . $foodType->name . ', id为: ' . $foodType->id);
        return new FoodTypeResource($foodType);
    }
}
